import React, { useRef, useState, useEffect } from 'react';
import { Dialog, Form, Input, Select, Radio, MessagePlugin, Upload, Button } from 'tdesign-react';
import { FormInstanceFunctions } from 'tdesign-react/es/form/type';
import { UploadFile } from 'tdesign-react/es/upload/type';
import { registerUserAPI, importUsersAPI } from '@/api/user.api';
import { getDepartmentListAPI } from '@/api/department.api';
import { FormRule } from 'tdesign-react/es/form/type';

const { FormItem } = Form;

interface RegisterDialogProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

interface RegisterData {
  studentId: string;
  name: string;
  role: string;
  gender: string;
  phone: string;
  email: string;
  departmentId: string;
}

interface Department {
  id: number;
  name: string;
  code: string;
}

const RegisterDialog: React.FC<RegisterDialogProps> = ({ visible, onClose, onSuccess }) => {
  const formRef = useRef<FormInstanceFunctions>();
  const [activeTab, setActiveTab] = useState<'single' | 'batch'>('single');
  const [uploading, setUploading] = useState(false);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取部门列表
  useEffect(() => {
    const fetchDepartments = async () => {
      try {
        setLoading(true);
        const res = await getDepartmentListAPI();
        if (res.data?.data) {
          setDepartments(res.data.data);
        }
      } catch (error) {
        MessagePlugin.error('获取部门列表失败');
      } finally {
        setLoading(false);
      }
    };

    if (visible) {
      fetchDepartments();
    }
  }, [visible]);

  // 表单验证规则
  const rules: Record<string, FormRule[]> = {
    studentId: [
      { required: true, message: '请输入学/工号', type: 'error' },
      { pattern: /^\d{11}$/, message: '请输入11位数字学/工号', type: 'error' }
    ],
    name: [{ required: true, message: '请输入姓名', type: 'error' }],
    role: [{ required: true, message: '请选择角色', type: 'error' }],
    gender: [{ required: true, message: '请选择性别', type: 'error' }],
    phone: [
      { required: true, message: '请输入手机号', type: 'error' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', type: 'error' }
    ],
    email: [
      { required: true, message: '请输入邮箱', type: 'error' },
      { pattern: /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱地址', type: 'error' }
    ],
    departmentId: [{ required: true, message: '请选择部门', type: 'error' }],
  };

  // 单一用户注册
  const handleSingleRegister = async () => {
    const valid = await formRef.current?.validate();
    if (valid === true) {
      try {
        const formData = formRef.current?.getFieldsValue(true);
        await registerUserAPI(formData as RegisterData).then((res) => {
          if (res.status === 201) {
            MessagePlugin.success('用户注册成功');
            onSuccess();
            onClose();
          } else {
            MessagePlugin.error(res.data.message || '注册失败');
          }
        }).catch((error: any) => {
          MessagePlugin.error(error.response.data.message || '注册失败');
        });
      } catch (error: any) {
        MessagePlugin.error(error.message || '注册失败');
      }
    }
  };

  // 处理文件上传
  const handleUpload = async (file: UploadFile) => {
    if (!file.raw) {
      MessagePlugin.error('文件上传失败');
      return;
    }

    // 验证文件类型
    const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.raw.type === 'application/vnd.ms-excel';
    if (!isExcel) {
      MessagePlugin.error('请上传Excel文件（.xlsx或.xls格式）');
      return;
    }

    // 验证文件大小（限制为10MB）
    const isLt10M = file.raw.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      MessagePlugin.error('文件大小不能超过10MB');
      return;
    }

    try {
      setUploading(true);
      // 确保文件对象正确传递
      const fileToUpload = new File([file.raw], file.raw.name, {
        type: file.raw.type
      });

      const response = await importUsersAPI(fileToUpload);
      if (response.data?.success) {
        MessagePlugin.success('批量导入成功');
        onSuccess();
        onClose();
      } else {
        MessagePlugin.error(response.data?.message || '导入失败');
      }
    } catch (error: any) {
      console.error('上传错误:', error);
      MessagePlugin.error(error.response?.data?.message || '导入失败，请检查文件格式是否正确');
    } finally {
      setUploading(false);
    }
  };

  // 下载模板
  const handleDownloadTemplate = async () => {
    try {
      const url = "http://localhost:3000/public/templates/user_import_template.xlsx";
      const link = document.createElement('a');
      link.href = url;
      link.download = 'user_import_template.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error: any) {
      MessagePlugin.error('模板下载失败');
    }
  };

  return (
    <Dialog
      header="用户注册"
      visible={visible}
      onClose={onClose}
      width={800}
      footer={
        <>
          <Button theme="default" onClick={onClose}>
            取消
          </Button>
          {activeTab === 'single' && (
            <Button theme="primary" onClick={handleSingleRegister}>
              确定
            </Button>
          )}
        </>
      }
    >
      <div style={{ marginBottom: '20px' }}>
        <Radio.Group value={activeTab} onChange={(value) => setActiveTab(value as 'single' | 'batch')}>
          <Radio.Button value="single">单一注册</Radio.Button>
          <Radio.Button value="batch">批量导入</Radio.Button>
        </Radio.Group>
      </div>

      {activeTab === 'single' ? (
        <Form ref={formRef} rules={rules} labelWidth={100}>
          <FormItem label="学/工号" name="studentId">
            <Input placeholder="请输入11位数字学/工号" />
          </FormItem>
          <FormItem label="姓名" name="name">
            <Input placeholder="请输入姓名" />
          </FormItem>
          <FormItem label="角色" name="role">
            <Select
              options={[
                { label: '学生', value: 'student' },
                { label: '教师', value: 'teacher' },
                { label: '管理员', value: 'admin' },
              ]}
              placeholder="请选择角色"
            />
          </FormItem>
          <FormItem label="性别" name="gender">
            <Radio.Group>
              <Radio value="male">男</Radio>
              <Radio value="female">女</Radio>
            </Radio.Group>
          </FormItem>
          <FormItem label="手机号" name="phone">
            <Input placeholder="请输入手机号" />
          </FormItem>
          <FormItem label="邮箱" name="email">
            <Input placeholder="请输入邮箱" />
          </FormItem>
          <FormItem label="部门" name="departmentId">
            <Select
              loading={loading}
              options={departments.map(dept => ({
                label: `${dept.name} (${dept.code})`,
                value: String(dept.id)
              }))}
              placeholder="请选择部门"
            />
          </FormItem>
        </Form>
      ) : (
        <div>
          <div style={{ marginBottom: '16px' }}>
            <Button theme="default" onClick={handleDownloadTemplate}>
              下载导入模板
            </Button>
            <span style={{ marginLeft: '8px', color: '#999' }}>
              请先下载模板，按照模板格式填写用户信息后再上传
            </span>
          </div>
          <Upload
            accept=".xlsx,.xls"
            autoUpload={false}
            disabled={uploading}
            multiple={false}
            showUploadProgress
            theme="file"
            tips="支持 .xlsx 和 .xls 格式的文件，文件大小不超过10MB"
            onChange={(files) => files[0] && handleUpload(files[0] as UploadFile)}
          >
            <Button loading={uploading} theme="primary" disabled={uploading}>
              {uploading ? '正在上传...' : '选择表格文件'}
            </Button>
          </Upload>
        </div>
      )}
    </Dialog>
  );
};

export default RegisterDialog; 